package game;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.JPanel;

class Board extends JPanel{

	private IGUIEventListener listener;
	private GridLayout layout = new GridLayout();
	private Map<Point,Grid> grids = new HashMap();
	
	public Board(IGUIEventListener listener){
		setLayout(layout);
		this.listener = listener;
	}
	
	public void init(Point size)
	{
		grids.clear();
		this.removeAll();
		layout.setColumns(size.x);
		layout.setRows(size.y);
		layout.setHgap(0);
		layout.setVgap(0);
		for(int y = 0; y < size.y; y++)
		{
			for(int x = 0; x < size.x; x++)
			{
				Point l = new Point(x,y);
				Grid grid = new Grid(listener,l);
				grids.put(l, grid);
				add(grid);
			}
		}
		this.setVisible(true);
	}
	public boolean getLocationEnable(Point location){
		assert grids.containsKey(location);
		return grids.get(location).isEnabled();
	}
	
	public void setLocationEnable(Point location,boolean state)
	{
		assert grids.containsKey(location);
		grids.get(location).setEnabled(state);
	}
	
	public void setAllLocationEnable(boolean state)
	{
		for(Grid g : grids.values()){
			g.setEnabled(state);
		}
	}

}
class Grid extends JPanel implements MouseListener {
	private IGUIEventListener listener;
	private Point location;
	public Grid(IGUIEventListener listener, Point location) {
		super();
		this.listener = listener;
		this.location = location;
		this.addMouseListener(this);
	}
	@Override
	public void paint(Graphics g) {
		super.paint(g);
		listener.OnPaint(g, new Point(getSize().width,getSize().height), location);
		if(!isEnabled())
		{
			g.setColor(new Color(0.0f,0.0f,0.0f,0.5f));
			g.fillRect(0, 0, this.getWidth(), this.getHeight());
		}
	}
	@Override
	public void mouseClicked(MouseEvent arg0) {
		if(isEnabled())
			listener.OnLocationSelected(location);
		else
			listener.OnCancel();
		this.getParent().repaint();
	}
	@Override
	public void mouseEntered(MouseEvent arg0) {}
	@Override
	public void mouseExited(MouseEvent arg0) {}
	@Override
	public void mousePressed(MouseEvent arg0) {}
	@Override
	public void mouseReleased(MouseEvent arg0) {}
}